Followed the samples in OpenCV page http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_calib3d/py_calibration/py_calibration.html
checkerboard (7x10) from http://opencv.jp/sample/pics/chesspattern_7x10.pdf
In [1]:
import numpy as np
import cv2
import glob
In [2]:
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 0.001)
In [3]:
objp = np.zeros((7*10, 3), np.float32)
objp[:, :2] = np.mgrid[0:7, 0:10].T.reshape(-1, 2)
In [4]:
objpoints = []
imgpoints = []
In [5]:
cap = cv2.VideoCapture(0)
In [6]:
# capture images and store them into calibration folder after space key is hit
c = 0
while True:
ret, im = cap.read()
if not ret:
continue
cv2.imshow('video test', im)
key = cv2.waitKey(10)
if key == 27:
break;
if key == ord(' '):
cv2.imwrite('calibration/vid_result'+str(c)+'.jpg', im)
c += 1
In [7]:
images = glob.glob('./calibration/*.jpg')
In [42]:
# find corners
for fname in images:
img = cv2.imread(fname)
grayimg = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, corners = cv2.findChessboardCorners(grayimg, (7, 10), None)
if ret:
objpoints.append(objp)
cv2.cornerSubPix(grayimg, corners, (11, 11), (-1, -1), criteria)
imgpoints.append(corners)
# cv2.drawChessboardCorners(img, (7, 10), corners, ret)
# cv2.imshow('img', img)
# cv2.waitKey(5000)
cv2.destroyAllWindows()
In [18]:
ret, mtx, dist, rvecs, tvecs = cv2.calibrateCamera(objpoints, imgpoints, grayimg.shape[::-1], None, None)
In [34]:
img = cv2.imread('calibration/vid_result1.jpg')
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
In [35]:
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
In [36]:
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
cv2.imwrite('calibration/calibresult.png', dst)
Out[36]:
In [41]:
cv2.imshow('calibrated', cv2.imread('calibration/calibresult.png'))
cv2.waitKey(5000)
cv2.destroyAllWindows()
In [28]:
# Show images without distortion
c = 0
while True:
ret, img = cap.read()
if not ret:
continue
h, w = img.shape[:2]
newcameramtx, roi = cv2.getOptimalNewCameraMatrix(mtx, dist, (w, h), 1, (w, h))
dst = cv2.undistort(img, mtx, dist, None, newcameramtx)
x, y, w, h = roi
dst = dst[y:y+h, x:x+w]
cv2.imshow('video test', dst)
key = cv2.waitKey(10)
if key == 27:
break;
if key == ord(' '):
cv2.imwrite('calibration/calibrated_result'+str(c)+'.jpg', dst)
cv2.destroyAllWindows()
In [ ]: